import ApiError from '../error/ApiError'

/**
 * 返回体拦截器
 */
const responseFilter = () => {
	return async (ctx, next) => {
		try {
			await next()
			responseFormatter(ctx)
		} catch (error) {
			// 如果异常类型是自定义API异常
			if (error instanceof ApiError) {
				ctx.status = 200
				ctx.body = {
					code: error.code,
					message: error.message,
				}
			} else {
				throw error
			}
		}
	}
}

const responseFormatter = (ctx) => {
    // 跳过拦截地址
    const norejectUrls = [/\/jinritemai\/callback\/shopbuy/, /\/dlyadminapi\/link\/binduser\/*/, /\/api\/alipay\/cb/]
	// ctx.status = 500

    if(norejectUrls.filter(item => item.test(ctx.url)).length) {
        ctx.body = ctx.body 
        return
    }
	if (ctx.status === 422) {
        ctx.status = 200
		ctx.body = {
			code: 42202,
			message: '缺少必要参数',
			errors: ctx.body,
		}
        return
	}
	if (ctx.body) {
		ctx.body = {
			code: 0,
			message: '请求成功',
			data: ctx.body,
		}
	} else {
		ctx.body = {
			code: 0,
			message: '请求成功',
		}
	}
}

export default responseFilter
